package com.esun.util;

import java.math.BigInteger;

import java.security.KeyFactory;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;

import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;


public class RSA {

	public static PublicKey getPublicKey(String modulus, String publicExponent) throws Exception {

		BigInteger m = new BigInteger(modulus);

		BigInteger e = new BigInteger(publicExponent);

		RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);

		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(keySpec);

		return publicKey;

	}

	public static PrivateKey getPrivateKey(String modulus, String privateExponent) throws Exception {

		BigInteger m = new BigInteger(modulus);

		BigInteger e = new BigInteger(privateExponent);

		RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);

		KeyFactory keyFactory = KeyFactory.getInstance("RSA");

		PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

		return privateKey;

	}

	/**
	 * Encrypt String.
	 * 
	 * @return byte[]
	 */
	public static byte[] encrypt(RSAPublicKey publicKey, byte[] data) {
		if (publicKey != null) {
			try {
					
				Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
				cipher.init(Cipher.ENCRYPT_MODE, publicKey);
				return cipher.doFinal(data);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/** */
	/**
	 * Basic decrypt method
	 * 
	 * @return byte[]
	 */
	protected static byte[] decrypt(PrivateKey privateKey, byte[] obj) {
		if (privateKey != null) {
			try {
				Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
				cipher.init(Cipher.DECRYPT_MODE, privateKey);

				return cipher.doFinal(obj);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}